package com.sxsihe.heartmate;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.*;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.*;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.Iterator;

import android.widget.TextView;
import android.widget.Toast;
import cn.pedant.SweetAlert.widget.SweetAlertDialog;
import com.sxsihe.heartmate.util.SharePreferenceUtil;
import com.sxsihe.heartmate.view.CustomProgressDialog;
import com.sxsihe.heartmate.view.CustomWaittingDialog;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends FragmentActivity {
    public static MainActivity instance = null;
    private ViewPager mTabPager;
    private ImageView mTabImg;
    private ImageView mTab1, mTab2, mTab3, mTab4;
    private TextView t1, t2, t3, t4;
    private LinearLayout layout1, layout2, layout3, layout4;
    private int zero = 0;
    private int currIndex = 0;
    private int one;
    private int two;
    private int three;
    ArrayList<View> views = new ArrayList<View>();
    CustomProgressDialog pDialog;
    SharePreferenceUtil spu;
    JSONObject userInfo;
    CustomWaittingDialog dialog;
    DeviceView view1;
    HistoryView view2;
    UserInfoView view3;
    SettingsView view4;

    final static int COLOR_CHOOSE = 10;

//    private void requestPermission() {
//        if (Build.VERSION.SDK_INT >= 23) {
//            int checkAccessFinePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission_group);
//            if (checkAccessFinePermission != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
//                        REQUEST_PERMISSION_ACCESS_LOCATION);
//                 return;
//            }
//         }
//        //做下面该做的事
//    }
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);


        if (spu == null) {
            spu = SharePreferenceUtil.getInstance(this);
        }
        dialog = new CustomWaittingDialog(this, R.anim.communication_waitting);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        instance = this;
        mTabPager = (ViewPager) findViewById(R.id.tabpager);
        mTabPager.setOnPageChangeListener(new MyOnPageChangeListener());

        mTab1 = (ImageView) findViewById(R.id.img_device);
        t1 = (TextView) findViewById(R.id.title_device);

        mTab2 = (ImageView) findViewById(R.id.img_history);
        t2 = (TextView) findViewById(R.id.title_history);
        mTab3 = (ImageView) findViewById(R.id.img_user);
        t3 = (TextView) findViewById(R.id.title_user);
        mTab4 = (ImageView) findViewById(R.id.img_settings);
        t4 = (TextView) findViewById(R.id.title_settings);
        //mTabImg = (ImageView) findViewById(R.id.img_tab_now);
        mTab1.setOnClickListener(new MyOnClickListener(0));
        mTab2.setOnClickListener(new MyOnClickListener(1));
        mTab3.setOnClickListener(new MyOnClickListener(2));
        mTab4.setOnClickListener(new MyOnClickListener(3));

        layout1 = (LinearLayout) findViewById(R.id.layout_device);
        layout2 = (LinearLayout) findViewById(R.id.layout_history);
        layout3 = (LinearLayout) findViewById(R.id.layout_user);
        layout4 = (LinearLayout) findViewById(R.id.layout_settings);

        //mTabImg = (ImageView) findViewById(R.id.img_tab_now);
        layout1.setOnClickListener(new MyOnClickListener(0));
        layout2.setOnClickListener(new MyOnClickListener(1));
        layout3.setOnClickListener(new MyOnClickListener(2));
        layout4.setOnClickListener(new MyOnClickListener(3));

        Display currDisplay = getWindowManager().getDefaultDisplay();
        int displayWidth = currDisplay.getWidth();
        int displayHeight = currDisplay.getHeight();

        LayoutInflater mLi = LayoutInflater.from(this);
        view1 = new DeviceView(this);
        view2 = new HistoryView(this);
        view3 = new UserInfoView(this);
        view4 = new SettingsView(this);

        views.add(view1);
        views.add(view2);
        views.add(view3);
        views.add(view4);
        pDialog = new CustomProgressDialog(this, "正在加载中", R.anim.connect_waitting);
        PagerAdapter mPagerAdapter = new PagerAdapter() {

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public int getCount() {
                return views.size();
            }

            @Override
            public void destroyItem(View container, int position, Object object) {
                ((ViewPager) container).removeView(views.get(position));
            }

            @Override
            public Object instantiateItem(View container, int position) {
                ((ViewPager) container).addView(views.get(position));
                return views.get(position);
            }
        };
        mTabPager.setAdapter(mPagerAdapter);
        showTip();
    }

    public static void changeView() {

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case COLOR_CHOOSE:
                if (resultCode == RESULT_OK) {
                    int color = data.getExtras().getInt("color");
                    String item = data.getExtras().getString("item");
                    view4.setColor(item, color);
                }
                break;
        }
//        switch (requestCode) {
//            //跳转时带的标识符 0 表示RealtimeActivity结束
//            case 0:
//                if (data != null) {
//                    String result = data.getExtras().getString("isRecord");
//                    if (result != null && result.equals("1")) {
//                        mTabPager.setCurrentItem(1);
//                    }
//                }
//                break;
//            default:
//                break;
//        }
    }

    public void onResume() {
        super.onResume();
        ((UserInfoView) views.get(2)).getUserInfo();
    }


    public void onBackPressed() {
//        new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
//                .setTitleText("确定要退出吗")
//                .setCancelText("继续使用")
//                .setConfirmText("确定退出")
//                .showCancelButton(true)
//                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                    @Override
//                    public void onClick(SweetAlertDialog sDialog) {
//                        sDialog.dismiss();
//                    }
//                })
//                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                    @Override
//                    public void onClick(SweetAlertDialog sDialog) {
//                        sDialog.dismiss();
//                        android.os.Process.killProcess(android.os.Process.myPid());
//                    }
//                }).show();
        final AlertDialog myDialog = new AlertDialog.Builder(this).create();
        myDialog.show();
        myDialog.getWindow().setContentView(R.layout.exit_warning);
        myDialog.getWindow()
                .findViewById(R.id.cancel)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog.dismiss();
                    }
                });
        myDialog.getWindow()
                .findViewById(R.id.confirm)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog.dismiss();
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                });
    }

    public void showTip() {
        if (currIndex == 1) {
//            ((HistoryView) views.get(currIndex)).showTip();
        }
    }

    public void showWaitting() {
        dialog.showWaitting();
    }

    public void hideWaitting() {
        dialog.hideWaitting();
    }

    public void updateUserInfoResult(String result) {
        dialog.hideWaitting();
        if ("".equals(result)) {
            new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("出错了")
                    .setContentText("通讯异常")
                    .show();
            ((UserInfoView) views.get(2)).refreshUserInfo(userInfo.toString());
        } else {
            try {
                JSONObject json = new JSONObject(result);
                if (json.getBoolean("success")) {
                    new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
                            .setTitleText("成功")
                            .setContentText("更新成功")
                            .show();

                } else {
                    new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("出错了")
                            .setContentText("用户名密码不匹配")
                            .show();
                    ((UserInfoView) views.get(2)).refreshUserInfo(userInfo.toString());
                }

            } catch (JSONException e) {
                new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("失败")
                        .setContentText("更新失败")
                        .show();
                ((UserInfoView) views.get(2)).refreshUserInfo(userInfo.toString());
                e.printStackTrace();
            }
        }
    }


    public void getUserInfo(String result) {
        dialog.hideWaitting();
        if ("".equals(result)) {
            Toast.makeText(MainActivity.this, "通讯异常", Toast.LENGTH_SHORT).show();
        } else {
            try {
                userInfo = new JSONObject(result);
                if (userInfo.getBoolean("success")) {
                    Toast.makeText(MainActivity.this, "获取用户数据成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "获取用户数据失败", Toast.LENGTH_SHORT).show();
                }
                ((UserInfoView) views.get(2)).refreshUserInfo(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    public class MyOnClickListener implements View.OnClickListener {
        private int index = 0;

        public MyOnClickListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            mTabPager.setCurrentItem(index, false);
        }
    }

    ;

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageSelected(int arg0) {
            if (mTab1 == null || mTab2 == null || mTab3 == null || mTab4 == null) {
                return;
            }
            switch (arg0) {
                case 0:
                    mTab1.setImageDrawable(getResources().getDrawable(R.drawable.tab_device_pressed));
                    mTab2.setImageDrawable(getResources().getDrawable(R.drawable.tab_history_normal));
                    mTab3.setImageDrawable(getResources().getDrawable(R.drawable.tab_user_normal));
                    mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal));

                    t1.setTextColor(Color.parseColor("#0095f7"));
                    t2.setTextColor(Color.parseColor("#B3B3B3"));
                    t3.setTextColor(Color.parseColor("#B3B3B3"));
                    t4.setTextColor(Color.parseColor("#B3B3B3"));
                    break;
                case 1:
                    mTab2.setImageDrawable(getResources().getDrawable(R.drawable.tab_history_pressed));
                    mTab1.setImageDrawable(getResources().getDrawable(R.drawable.tab_device_normal));
                    mTab3.setImageDrawable(getResources().getDrawable(R.drawable.tab_user_normal));
                    mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal));
                    t1.setTextColor(Color.parseColor("#B3B3B3"));
                    t2.setTextColor(Color.parseColor("#0095f7"));
                    t3.setTextColor(Color.parseColor("#B3B3B3"));
                    t4.setTextColor(Color.parseColor("#B3B3B3"));
                    break;
                case 2:
                    mTab3.setImageDrawable(getResources().getDrawable(R.drawable.tab_user_pressed));
                    mTab1.setImageDrawable(getResources().getDrawable(R.drawable.tab_device_normal));
                    mTab2.setImageDrawable(getResources().getDrawable(R.drawable.tab_history_normal));
                    mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal));
                    t1.setTextColor(Color.parseColor("#B3B3B3"));
                    t2.setTextColor(Color.parseColor("#B3B3B3"));
                    t3.setTextColor(Color.parseColor("#0095f7"));
                    t4.setTextColor(Color.parseColor("#B3B3B3"));
                    break;
                case 3:
                    mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_pressed));
                    mTab1.setImageDrawable(getResources().getDrawable(R.drawable.tab_device_normal));
                    mTab2.setImageDrawable(getResources().getDrawable(R.drawable.tab_history_normal));
                    mTab3.setImageDrawable(getResources().getDrawable(R.drawable.tab_user_normal));
                    t1.setTextColor(Color.parseColor("#B3B3B3"));
                    t2.setTextColor(Color.parseColor("#B3B3B3"));
                    t3.setTextColor(Color.parseColor("#B3B3B3"));
                    t4.setTextColor(Color.parseColor("#0095f7"));
                    break;
            }
            currIndex = arg0;
            showTip();
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }
}
